package com.wechat.back.service;

import com.wechat.back.config.AmapWeatherConfig;
import com.wechat.back.pojo.weather.Forecast;
import com.wechat.back.pojo.weather.WeatherForecast;
import com.wechat.back.pojo.weather.WeatherResponse;
import com.wechat.back.pojo.weather.Cast;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class WeatherService {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private AmapWeatherConfig amapWeatherConfig;

    public List<WeatherForecast> getWeatherForecast(String city) {
        String url = amapWeatherConfig.getUrl() +
                "?city=" + city +
                "&key=" + amapWeatherConfig.getKey() +
                "&extensions=all";
        System.out.println(url);

        WeatherResponse response = restTemplate.getForObject(url, WeatherResponse.class);
        if (response == null || response.getForecasts() == null || response.getForecasts().isEmpty()) {
            return Collections.emptyList();
        }

        Forecast forecast = response.getForecasts().get(0);
        List<Cast> casts = forecast.getCasts();
        if (casts == null || casts.isEmpty()) {
            return Collections.emptyList();
        }

        List<WeatherForecast> weatherForecasts = new ArrayList<>();
        for (Cast cast : casts) {
            WeatherForecast forecastData = new WeatherForecast();
            forecastData.setDate(cast.getDate());
            forecastData.setWeek(cast.getWeek());
            forecastData.setDayWeather(cast.getDayweather());
            forecastData.setNightWeather(cast.getNightweather());
            forecastData.setDayTemp(cast.getDaytemp());
            forecastData.setNightTemp(cast.getNighttemp());
            forecastData.setDayWind(cast.getDaywind());
            forecastData.setNightWind(cast.getNightwind());
            forecastData.setDayPower(cast.getDaypower());
            forecastData.setNightPower(cast.getNightpower());
            weatherForecasts.add(forecastData);
        }

        return weatherForecasts;
    }
}
